<template>
  <div class="layout">
    <div class="left">
      <h1>请求数据</h1>
      <textarea v-model="inputText" cols="100%" rows="10"></textarea>
      <div class="operate">
        <button @click="initWs">连接</button>
        <button @click="closeWs">断开</button>
      </div>

    </div>
    <div class="right">
      <h1>响应结果</h1>
      <textarea v-model="outputText" cols="100%" rows="10"></textarea>
    </div>
  </div>

</template>

<script>
const wsUrl = "ws://localhost:7070";

export default {
  name: 'HomeView',
  data() {
    return {
      inputText: '',
      outputText: '',
      socket: null
    }
  },
  methods: {
    sendMsg(msg) {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        let param = {
          text: msg
        }
        this.socket.send(JSON.stringify(param));
      } else {
        console.error('WebSocket 连接未建立或已关闭');
      }
    },
    initWs() {
      if (!("WebSocket" in window)) {
        console.log('浏览器不支持WebSocket')
        return null
      }

      this.socket = new WebSocket(wsUrl);
      this.socket.onopen = () => {
        console.log('WebSocket 连接已建立...');
      };
      this.socket.onmessage = (event) => {
        console.log('onmessage:', event);
        this.outputText = event.data;
      };
      this.socket.onclose = () => {
        console.log('WebSocket 连接已关闭');
        this.socket = null;
      };
      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
    },
    closeWs() {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.close();
      } else {
        console.error('WebSocket 连接未建立或已关闭');
      }
    }
  },
  created() {
    // 在组件创建时初始化 WebSocket 连接
    this.initWs();

    // 监听 inputText 变量的变化，变化时发送消息给后端
    this.$watch('inputText', (newValue, oldValue) => {
      if (newValue !== oldValue) {
        this.sendMsg(newValue);
      }
    });
  },
  beforeDestroy() {
    // 在组件销毁前关闭 WebSocket 连接
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.close();
    }
  }
}
</script>


<style>
.layout {
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;

}

.left {
  flex: 1;
  padding: 2em;
  display: flex;
  flex-direction: column;
}

.right {
  flex: 1;
  border-left: 2px solid #000;
  padding: 2em;
}

.operate {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

button {
  margin-top: 1em;
  margin-left: 1em;
  width: fit-content;

}
</style>
